<template>
  <div class="member-container">
    <div class="member-card" 
      :class="{ highlighted: isHighlighted }" 
      :data-member-id="member?.id" 
      @click="handleMemberClick"
    >
      <div class="member-info">
        <div class="avatar-container">
          <el-upload
            v-if="isAdmin"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="(res) => handleAvatarSuccess(res, member)"
            :before-upload="beforeAvatarUpload"
            action="/api/files/upload"
            :headers="uploadHeaders"
            name="file"
          >
            <el-avatar :size="60" :src="member?.avatarUrl" class="clickable-avatar">
              {{ member?.name?.charAt(0) || '?' }}
            </el-avatar>
          </el-upload>
          <el-avatar v-else :size="60" :src="member?.avatarUrl">
            {{ member?.name?.charAt(0) || '?' }}
          </el-avatar>
        </div>
        <h3>{{ member?.name || '未知' }}</h3>
        <p>{{ formatDate(member?.birthDate) }} - {{ member?.deathDate ? formatDate(member?.deathDate) : '在世' }}</p>
        <p class="role">
          {{ member?.role || '未知角色' }}
        </p>
        <div v-if="isAdmin" class="member-actions">
          <el-button-group>
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="$emit('edit', member)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              :icon="Plus"
              @click="$emit('addSpouse', member)"
            >
              添加配偶
            </el-button>
            <el-button
              size="small"
              type="warning"
              :icon="Plus"
              @click="$emit('addChild', member)"
            >
              添加子女
            </el-button>
            <el-button
              v-if="!isAncestor"
              size="small"
              type="danger"
              :icon="Delete"
              @click="$emit('deleteChild', member)"
            >
              删除
            </el-button>
          </el-button-group>
        </div>
      </div>
      
      <div v-if="member?.spouse" class="spouse-container">
        <div class="marriage-line">
          <div class="couple-icon">
            <i class="couple-symbol">💕</i>
          </div>
          <span class="marriage-date">
            {{ formatDate(member?.spouse?.marriageDate) }}
          </span>
        </div>
        <div class="member-info">
          <div class="avatar-container">
            <el-upload
              v-if="isAdmin"
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="(res) => handleAvatarSuccess(res, member.spouse)"
              :before-upload="beforeAvatarUpload"
              action="/api/files/upload"
              :headers="uploadHeaders"
              name="file"
            >
              <el-avatar :size="60" :src="member?.spouse?.avatarUrl" class="clickable-avatar">
                {{ member?.spouse?.name?.charAt(0) || '?' }}
              </el-avatar>
            </el-upload>
            <el-avatar v-else :size="60" :src="member?.spouse?.avatarUrl">
              {{ member?.spouse?.name?.charAt(0) || '?' }}
            </el-avatar>
          </div>
          <h3>{{ member?.spouse?.name || '未知' }}</h3>
          <p>{{ formatDate(member?.spouse?.birthDate) }} - {{ member?.spouse?.deathDate ? formatDate(member?.spouse?.deathDate) : '在世' }}</p>
          <p class="role">
            {{ member?.spouse?.role || '未知角色' }}
          </p>
          <div v-if="isAdmin" class="member-actions">
            <el-button-group>
              <el-button
                size="small"
                type="primary"
                :icon="Edit"
                @click="$emit('edit', member.spouse)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                :icon="Delete"
                @click="$emit('deleteSpouse', member)"
              >
                删除
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>

    <div v-if="member?.children?.length > 0" class="children-container">
      <div class="vertical-line"></div>
      <div class="horizontal-line"></div>
      <div class="children-list">
        <family-member
          v-for="child in member.children"
          :key="child?.id || index"
          :member="child"
          :is-admin="isAdmin"
          :is-highlighted="highlightedMember?.id === child.id"
          @edit="$emit('edit', $event)"
          @add-spouse="$emit('addSpouse', $event)"
          @add-child="$emit('addChild', $event)"
          @delete-spouse="$emit('deleteSpouse', $event)"
          @delete-child="$emit('deleteChild', $event)"
          @handle-upload="$emit('handleUpload', $event)"
          @member-click="$emit('member-click', $event)"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useStore } from 'vuex'
import { Edit, Plus, Delete, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'FamilyMember',
  props: {
    member: {
      type: Object,
      required: true
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    isAncestor: {
      type: Boolean,
      default: false
    },
    isHighlighted: {
      type: Boolean,
      default: false
    },
    highlightedMember: {
      type: Object,
      default: null
    }
  },
  emits: ['edit', 'addSpouse', 'addChild', 'deleteSpouse', 'deleteChild', 'handleUpload', 'member-click'],
  setup() {
    const store = useStore()
    const uploadHeaders = computed(() => ({
      'Authorization': `Bearer ${store.state.token}`
    }))

    return {
      uploadHeaders,
      Edit,
      Plus,
      Delete,
      Upload
    }
  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      try {
        return new Date(date).toLocaleDateString()
      } catch (error) {
        console.error('日期格式化错误:', error)
        return ''
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    handleAvatarSuccess(res, targetMember = null) {
      if (res.code === 200 && res.data?.fileUrl) {
        this.$emit('handleUpload', {
          memberId: targetMember ? targetMember.id : this.member.id,
          avatarUrl: res.data.fileUrl
        })
      } else {
        ElMessage.error(res.message || '头像上传失败')
      }
    },
    handleMemberClick(event) {
      if (event.target.closest('.member-actions') || 
          event.target.closest('.avatar-container') ||
          event.target.closest('button') ||
          event.target.closest('input')) {
        return
      }
      
      event.stopPropagation()
      
      console.log('Member clicked in component:', this.member.id)
      
      this.$emit('member-click', {
        memberId: this.member.id
      })

      event.preventDefault()
    }
  }
}
</script>

<style scoped>
.member-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.member-card {
  display: flex;
  gap: 20px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.member-card .member-info {
  padding: 15px;
  border-radius: 8px;
  background-color: v-bind("member?.deathDate ? 'rgba(144, 147, 153, 0.2)' : (member?.gender === 'male' ? 'rgba(64, 158, 255, 0.2)' : 'rgba(255, 182, 193, 0.3)')");
  border: 1px solid v-bind("member?.deathDate ? 'rgba(144, 147, 153, 0.3)' : (member?.gender === 'male' ? 'rgba(64, 158, 255, 0.3)' : 'rgba(255, 182, 193, 0.4)')");
}

.spouse-container .member-info {
  background-color: v-bind("member?.spouse?.deathDate ? 'rgba(144, 147, 153, 0.2)' : (member?.spouse?.gender === 'male' ? 'rgba(64, 158, 255, 0.2)' : 'rgba(255, 182, 193, 0.3)')");
  border-color: v-bind("member?.spouse?.deathDate ? 'rgba(144, 147, 153, 0.3)' : (member?.spouse?.gender === 'male' ? 'rgba(64, 158, 255, 0.3)' : 'rgba(255, 182, 193, 0.4)')");
}

.member-card.highlighted {
  box-shadow: 0 0 20px rgba(74, 144, 226, 0.5);
  transform: scale(1.05);
  background-color: #ecf5ff;
  border: 2px solid #409eff;
  transition: all 0.3s ease;
}

.member-info {
  text-align: center;
  min-width: 200px;
}

.avatar-container {
  margin-bottom: 10px;
  position: relative;
}

.avatar-uploader {
  margin-top: 10px;
}

h3 {
  margin: 10px 0;
  color: #303133;
}

p {
  margin: 5px 0;
  color: #606266;
}

.role {
  color: #909399;
  font-size: 14px;
}

.member-actions {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 8px;
}

.member-actions :deep(.el-button) {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 13px;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.member-actions :deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
}

.member-actions :deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
}

.member-actions :deep(.el-button--warning) {
  background: linear-gradient(135deg, #e6a23c 0%, #cf9236 100%);
}

.member-actions :deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c 0%, #e64242 100%);
}

.member-actions :deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.member-actions :deep(.el-button:active) {
  transform: translateY(0);
}

.member-actions :deep(.el-button .el-icon) {
  margin-right: 4px;
  font-size: 14px;
}

.spouse-container {
  display: flex;
  align-items: center;
}

.marriage-line {
  width: 50px;
  height: 2px;
  background: transparent;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 0;
}

.couple-icon {
  position: absolute;
  top: -12px;
  left: 50%;
  transform: translateX(-50%);
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.couple-symbol {
  font-size: 24px;
  color: #ff69b4;
  font-style: normal;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.8);
  line-height: 1;
}

.marriage-date {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  background: transparent;
  padding: 2px 6px;
}

.children-container {
  position: relative;
  margin-top: 20px;
}

.vertical-line {
  width: 2px;
  height: 20px;
  background: #dcdfe6;
  margin: 0 auto;
}

.horizontal-line {
  width: 100%;
  height: 2px;
  background: #dcdfe6;
  position: absolute;
  top: 20px;
}

.children-list {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
}

.clickable-avatar {
  cursor: pointer;
  transition: all 0.3s ease;
}

.clickable-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style> 